package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WeChatPayUtil weChatPayUtil;
    @Autowired
    WebSocketServer webSocketServer;
    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //先获取当前用户id
        Long userId= BaseContext.getCurrentId();
        //判断当前地址蒲是否存在
          //查询地址蒲
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //判断当前用户的购物车的商品项是否为0
        ShoppingCart shoppingCart=new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if(list.size()==0||list==null){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向orders插入一条数据
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(1);
        orders.setPayStatus(0);
        orders.setAddressBookId(addressBook.getId());
        orders.setAddress(addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orderMapper.insert(orders);
        Long id=orders.getId();
        //向订单详细表插入n条数据
        List<OrderDetail> orderDetailList=new ArrayList<>();
        for(ShoppingCart cart:list){
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(id);
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //清空当前购物车数据
        shoppingCartMapper.deleteByUserId(userId);
        //封装数据发送给后端
        OrderSubmitVO orderSubmitVO=OrderSubmitVO.builder()
                .id(id)
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        //测试语音播报，没有声音就设置浏览器权限
        //支付成功后 服务端向客户端推送消息
        //推送的消息采用json格式 type id orderId content
//        Map map=new HashMap();//这里有一个所以发送两遍的1消息
//        map.put("type",1);
//        map.put("orderId",orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber()).getId());
//        map.put("outTradeNo","订单号："+ordersPaymentDTO.getOrderNumber());
//        String json= JSON.toJSONString(map);
//        webSocketServer.sendToAllClient(json);
//原来代码
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
        OrderPaymentVO vo=OrderPaymentVO.builder()
                .nonceStr("hmy23")
                .paySign("XianPi")
                .timeStamp(String.valueOf(System.currentTimeMillis()))
                .signType("hmy")
                .packageStr("package")
                .build();
        //模拟支付成功,用上面的假数据,调起成功支付的方法
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
        //支付成功后 服务端向客户端推送消息
        //推送的消息采用json格式 type id orderId content
        Map map=new HashMap();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("outTradeNo","订单号："+outTradeNo);
        String json= JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        Orders od=new Orders();
        od.setId(id);
        Orders order = orderMapper.getOrder(od);
        //TODO:先完成订单管理
        Map map=new HashMap();
        map.put("type",2);//2表示催单
        map.put("orderId",id);
        map.put("outTradeNo",order.getNumber());
        String json= JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
    /**
     * 搜索订单
     * @return
     */
    @Override
    public PageResult search(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //page别导错包了
        Page<OrderVO> pages = orderMapper.pageQuery(ordersPageQueryDTO);
        for(OrderVO orderVO:pages){
            //先根据查出来的订单项的订单号查询对应的菜品项
            List<OrderDetail> orderDetailList=orderDetailMapper.selectById(orderVO.getId());
            String orderDishes="";
            //构造orderDishes根据orderDetailList
            int index=0;
            for(OrderDetail orderDetail:orderDetailList){
                String name=orderDetail.getName(),number=orderDetail.getNumber().toString();
                if(orderDetailList.size()-1==index){
                    //最后一个元素
                    orderDishes+=name+"x"+number;
                }
                else {
                    orderDishes+=name+"x"+number+"、";
                    index++;
                }
            }
            orderVO.setOrderDishes(orderDishes);
        }
        return new PageResult(pages.getTotal(),pages.getResult());
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        Orders ordersDB =new Orders();
        ordersDB.setId(id);
        Orders orders=orderMapper.getOrder(ordersDB);
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        List<OrderDetail> orderDetailList=orderDetailMapper.selectById(orderVO.getId());
        orderVO.setOrderDetailList(orderDetailList);
        int index=0;
        String orderDishes="";
        for(OrderDetail orderDetail:orderDetailList){
           if(orderDetailList.size()-1==index){
               orderDishes+=orderDetail.getName()+"x"+orderDetail.getNumber();
           }
           else{
               orderDishes+=orderDetail.getName()+"x"+orderDetail.getNumber()+"、";
               index++;
           }
        }
        orderVO.setOrderDishes(orderDishes);
        return orderVO;
    }

    /**
     * 接单
     * @param id
     */
    @Override
    public void confirm(Long id) {
        Orders ordersDB =new Orders();
        ordersDB.setId(id);
        Orders orders=orderMapper.getOrder(ordersDB);
        if(orders==null){
            //订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }
    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders ordersDB =new Orders();
        ordersDB.setId(id);
        Orders orders=orderMapper.getOrder(ordersDB);
        if(orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(!orders.getStatus().equals(Orders.CONFIRMED)){
            //订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void reject(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders=new Orders();
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        BeanUtils.copyProperties(ordersRejectionDTO,orders);
        //查询需要被退款的订单 status=待派送状态 id=#{id}
        Orders od=orderMapper.getOrder(orders);
        if(od==null){
          throw  new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //改变订单的状态为取消 支付状态为退款 填入订单拒单的原因
        od.setStatus(Orders.CANCELLED);//改错了
        od.setPayStatus(Orders.REFUND);
        od.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        od.setCancelTime(LocalDateTime.now());//拒单也要设置取消原因
        orderMapper.update(od);
    }
    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders ordersDB =new Orders();
        ordersDB.setId(id);
        Orders orders=orderMapper.getOrder(ordersDB);
        if(orders==null){
            //订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancle(OrdersCancelDTO ordersCancelDTO) {
        Orders ordersDB =new Orders();
        ordersDB.setId(ordersCancelDTO.getId());
        Orders orders=orderMapper.getOrder(ordersDB);
        if(orders==null){
            //订单不存在
           throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //状态改为取消，支付状态改为退款，设置取消订单的原因
        orders.setStatus(Orders.CANCELLED);
        orders.setPayStatus(Orders.REFUND);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());//忘记设置取消时间
        orderMapper.update(orders);
    }

    /**
     * 统计各个状态的订单数
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        //统计待接单的数量
        Integer toBeConfirmed=orderMapper.countByStatus(Orders.TO_BE_CONFIRMED);
        //统计待派送的数量
        Integer confirmed=orderMapper.countByStatus(Orders.CONFIRMED);
        //统计派送中的数量
        Integer deliveryInProgress=orderMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> pages=orderMapper.pageQuery(ordersPageQueryDTO);
        for(OrderVO orderVO:pages){
           List<OrderDetail> list=orderDetailMapper.selectById(orderVO.getId());
           orderVO.setOrderDetailList(list);
        }
        return new PageResult(pages.getTotal(),pages.getResult());
    }

    /**
     * 再来一单 就是将商品重新放到购物车
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //根据订单id获取相同的订单信息以及对应的菜品表然后分别插入shoppingCart
        List<OrderDetail> orderDetailList=orderDetailMapper.selectById(id);
        List<ShoppingCart> shoppingCartList=new ArrayList<>();
        //向订单详细表插入n条数据
        for( OrderDetail orderDetail:orderDetailList){
             ShoppingCart shoppingCart=new ShoppingCart();
             BeanUtils.copyProperties(orderDetail,shoppingCart,"id");//忽略id属性
             shoppingCart.setCreateTime(LocalDateTime.now());
             shoppingCart.setUserId(BaseContext.getCurrentId());
             shoppingCartList.add(shoppingCart);
        }
        shoppingCartMapper.insertBatch(shoppingCartList);
    }


}
